<?php
Yii::import('application.extensions.image.CImageComponent');

/**
 * Description of CImageComponent
 *
 * @author Administrator
 */
class MrImageComponent extends CImageComponent
{
	public $cache;
	
	public $cache_file = null;
	
	public $thumb;
	
	public $base_path;

    public function init()
    {
        $this->cache = Yii::getPathOfAlias("webroot.picture.cache");
        if(!is_dir($this->cache)){
        	@mkdir($this->cache,0777,true);
        }
        
		$this->base_path = '/picture/thumb/';
		
     	$this->thumb = Yii::getPathOfAlias("webroot").$this->base_path ;
        if(!is_dir($this->thumb)){
        	@mkdir($this->thumb,0777,true);
        } 
        parent::init();
        
    }

    public function load($image)
    {
		if(!is_file($image)){
			$this->cache_file = $this->cache.'/'.md5($image);	
			if ($fp = @fopen($this->cache_file,'wb')) {
				@fwrite($fp, $image);
				@fclose($fp);
			} 
			$image = $this->cache_file ;
			
		}
        return parent::load($image);
    }
    
    public function getThumb($image,$width,$height,$filename = null ,$ext = null){
    	if (empty ( $filename )) {
			$filename = md5 ( $image );
		}
		if ($ext == null) {
			$ext = 'jpg';
		}
    
    	$folder = $width . 'x' . $height.'/';
    	 if(!is_dir($this->thumb.$folder)){
        	@mkdir($this->thumb.$folder,0777,true);
    	 }
		$filename = $folder . $filename . '.' . $ext;
		if (! file_exists (  $this->thumb .  $filename )) {
			
			$image = $this->load ( $image  );
			$image->resize ( $width, $height )->save (  $this->thumb . $filename );
		}
		return $this->base_path . $filename;
	}
	
	/**
	 * 
	 * @param Picture {EMongoGridFS} $image
	 * @param unknown_type $width
	 * @param unknown_type $height
	 * @param unknown_type $filename
	 * @param unknown_type $ext
	 */
    public function getThumbFS($image,$width,$height){

    	$folder = $width . 'x' . $height.'/';
    	 if(!is_dir($this->thumb.$folder)){
        	@mkdir($this->thumb.$folder,0777,true);
    	 }
    	$ext = isset($img->metadata['ext'])?$img->metadata['ext'] : 'jpg';
			
		$filename = $folder . $image->_id . '.' . $ext;
		if (! file_exists (  $this->thumb .  $filename )) {
			
			$image = $this->load ( $image->getBytes() );
			$image->resize ( $width, $height )->save (  $this->thumb . $filename );
		}
		return $this->base_path . $filename;
	}
	
	
	public function __destruct() {
    	
		try{
    	if( $this->cache_file)
    		@unlink(  $this->cache_file);
			
		}catch(Exception $e ){
			echo $e->getMessage();
		}
//    	parent::__destruct();
    }
}
?>
